import java.awt.Color;
import java.awt.Component;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.ComponentEvent;
import java.awt.event.KeyEvent;
import java.util.ArrayList;
import java.util.Vector;
import javax.swing.*;
import javax.swing.table.DefaultTableModel;
import java.awt.Component;
import java.awt.Dimension;
import java.awt.Rectangle;
import java.awt.event.AdjustmentEvent;
import java.awt.event.AdjustmentListener;
import java.awt.event.ComponentListener;
import java.awt.event.KeyListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.util.Comparator;
import javax.swing.table.TableRowSorter;

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/**
 *
 * @author tekoraik
 */
public class VistaConjPares extends JPanel {
    private JScrollPane jspTblPares;
    private JButton btnNuevoPar;
    private JButton btnEliminarPar;
    private JButton btnModificarPar;
    private JButton btnBuscarPar;
    private JTable tblPares;
    private SpringLayout layout;
    private SpringLayout layoutBotones;
    private SpringLayout layoutPares;
    private JPanel pares;
    private JTextField txtParI;
    private JTextField txtParC;
    private JLabel jlparI;
    private JLabel jlparC;
    private DefaultTableModel dtm;
    private JPanel pNoHayCP;
    private SpringLayout lyPanelNoHayCP;
    private JLabel lbNoHayCP;
    private CIConjPares cicp;
    private JDialog dgCargar;
    private JProgressBar jpbCargar;
    private SpringLayout layoutDgCargar;
    private AccionProgreso accionCargar;

    public VistaConjPares(CIConjPares controlador){
        cicp = controlador;
        inicializar();
    }
    public void inicializarTabla(String[][] conjpares) {
        layoutPares = new SpringLayout();
        tblPares = new JTable();

        tblPares.setModel(dtm);

        jspTblPares = new JScrollPane(tblPares);
        tblPares.setModel(dtm);

      
        for (int i = 0; i < conjpares.length; ++i) {
            dtm.addRow(conjpares[i]);
        }
        inicializarPanel();
        inicializarLayoutPares();
        montar();
    }
     public void inicializarTab() {
        dtm = construirTableModel(0);
        tblPares.setModel(dtm);

        //jspTblPares = new JScrollPane(tblPares);
        tblPares.setModel(dtm);

    }
    public void borrarIK(int i, int k){
        while (i<=(i+k) && i<dtm.getRowCount()){
            for (int j=0; j<dtm.getColumnCount(); j++){
                dtm.setValueAt("", i, j);
            }
            i++;
        }
    }
    public void rellenarIK(int i, int k,String[][] s){
        int j=0;
        int ii=i;
        while (ii<(i+k) && ii<dtm.getRowCount()){
            dtm.setValueAt(s[j][1], ii, 0);
            dtm.setValueAt(s[j][0], ii, 1);
            dtm.setValueAt(s[j][2], ii, 2);
            ii++;
            j++;
        }
    }
    public void nuevaTabla(int filas){
        dtm = construirTableModel(filas);
        tblPares.setModel(dtm);
        int k = cuantasFilas();
        
    }
    public int cuantasFilas(){
   
        return jspTblPares.getViewport().getHeight()/tblPares.getRowHeight()+1;
    }
    public int queFila(){
       return jspTblPares.getVerticalScrollBar().getValue()/tblPares.getRowHeight();
    }
     private void inicializarLayoutDgCargar(){
        dgCargar.getContentPane().setLayout(layoutDgCargar);
        layoutDgCargar.putConstraint(SpringLayout.HORIZONTAL_CENTER, jpbCargar, 0, SpringLayout.HORIZONTAL_CENTER, dgCargar.getContentPane());
        layoutDgCargar.putConstraint(SpringLayout.VERTICAL_CENTER, jpbCargar, 0, SpringLayout.VERTICAL_CENTER, dgCargar.getContentPane());
    }
     private DefaultTableModel construirTableModel(int i){
        DefaultTableModel tm;
        tm= new DefaultTableModel() {
        /*definimos que no se puede editar ninguna celda
          redefiniendo el metodo isCellEditable */
        @Override
        public boolean isCellEditable (int fila, int columna) {
            return false;
        }
        };
        tm.setRowCount(i);
        /*Comparator c = new Comparator() {
            public int compare(Object o1, Object o2) {
                int a = o1.hashCode();
                int b = o2.hashCode();
                if (a > b) return 1;
                else if (a < b) return -1;
                else return 0;
            }
        };*/
        
        tm.addColumn("Incorrecta");
        tm.addColumn("Correcta");
        tm.addColumn("Contador");
        
        //TableRowSorter sorter = new TableRowSorter(tm);
        //sorter.setComparator(2, c);       
        //tblPares.setRowSorter(sorter);
        
        return tm;
    }

    private void inicializar(){
        btnNuevoPar = new JButton("Nuevo Par");
        btnModificarPar = new JButton("Modificar Par");
        btnEliminarPar = new JButton("Eliminar Par");
        btnBuscarPar = new JButton("Buscar Par");
        txtParI = new JTextField ();
        txtParC = new JTextField ();
        jlparI = new JLabel ();
        jlparC = new JLabel ();

        dgCargar = new JDialog();
        layoutDgCargar = new SpringLayout();
        jpbCargar = new JProgressBar();
        jpbCargar.setStringPainted(true);
        jpbCargar.setPreferredSize(new Dimension(250,20));

        dgCargar.setLocationRelativeTo(this);
        dgCargar.setVisible(false);
        dgCargar.setSize(300,100);
        dgCargar.setModal(false);
        dgCargar.setTitle("Cargando...");
        
        tblPares = new JTable();


        /* ---- */

        btnNuevoPar.addActionListener(new ActionListener(){

        public void actionPerformed(ActionEvent e) {
             nuevoActionPerformed(e);
        }
        });
        btnModificarPar.addActionListener(new ActionListener(){

        public void actionPerformed(ActionEvent e) {
             modificarActionPerformed(e);
        }
        });
        btnEliminarPar.addActionListener(new ActionListener(){

        public void actionPerformed(ActionEvent e) {
             eliminarActionPerformed(e);
        }
        });
        btnBuscarPar.addActionListener(new ActionListener(){

        public void actionPerformed(ActionEvent e) {
             buscarActionPerformed(e);
        }
        });

        tblPares.addMouseListener(new MouseAdapter(){
            @Override
            public void mouseClicked(MouseEvent evt){
                tblMouseClicked(evt);
            }
        });

        pNoHayCP = new JPanel();
        lyPanelNoHayCP = new SpringLayout();
        lbNoHayCP=new JLabel("No hay ningun conjunto de pares");
        layoutPares = new SpringLayout();

        jspTblPares = new JScrollPane(tblPares);
        layout = new SpringLayout();
        layoutBotones = new SpringLayout();
        pares = new JPanel();
        layoutPares = new SpringLayout();
        lbNoHayCP.setHorizontalAlignment(SwingConstants.CENTER);
        lbNoHayCP.setVerticalAlignment(SwingConstants.CENTER);
        
        jspTblPares.getVerticalScrollBar().addAdjustmentListener(new AdjustmentListener(){

            @Override
            public void adjustmentValueChanged(AdjustmentEvent e) {
                cicp.refrescarTabla();
            }
        });
        
        inicializarPanel();
        inicializarPanelPares();
        inicializarLayoutPares();
        inicializarPanelNoHayCP();
        inicializarLayoutPanelNoHayCP();
        inicializarTab();
        inicializarLayout();
        inicializarLayoutDgCargar();
        montar();
    }
    public JProgressBar getBarraCarga(){
        return jpbCargar;
    }
    public void cerrarDialogo(){
        dgCargar.setVisible(false);
    }
    public void abrirDialogo(){

        dgCargar.setVisible(true);
    }
    public String preguntarRuta(Component cent,String tipo, String titulo){
        String ruta = "";
        int result;
        JFileChooser jfc = new JFileChooser();
        jfc.setApproveButtonText(tipo);
        jfc.setDialogType(JFileChooser.OPEN_DIALOG);
        jfc.setFileSelectionMode(JFileChooser.FILES_ONLY);
        jfc.setDialogTitle(titulo);
        result = jfc.showOpenDialog(cent);
        if (result == JFileChooser.APPROVE_OPTION){
            ruta = jfc.getSelectedFile().getPath();
        }
        return ruta;
    }
    

    private void tblMouseClicked (MouseEvent evt) {
        int[] sel = tblPares.getSelectedRows();
        String parI = String.valueOf(tblPares.getValueAt(sel[0], 0));
        String parC = String.valueOf(tblPares.getValueAt(sel[0], 1));
        txtParI.setText(parI);
        txtParC.setText(parC);
    }

    private void nuevoActionPerformed(ActionEvent e) {
        pares.setVisible(true);
        String [] aux = new String [3];
        aux[0] = String.valueOf(txtParI.getText());
        aux[1] = String.valueOf(txtParC.getText());
        aux[2] = "1";
        //tblPares.setModel(dtm);
        cicp.nuevoPar(aux[1], aux[0]);
        boolean encontrado = false;
        for (int i = 0; i < tblPares.getRowCount(); ++i){
            if (String.valueOf(tblPares.getValueAt(i, 0)).equals(aux[0]) &&
                    String.valueOf(tblPares.getValueAt(i, 1)).equals(aux[1]) && !encontrado) {
                    encontrado = true;
                    String [] res = new String[3];
                    res = cicp.buscarPar(aux[1], aux[0]);
                    if (res == null)dtm.removeRow(i);
                    else {
                        String aux2 = String.valueOf(res[2]);
                        tblPares.setValueAt(aux2, i, 2);
                    }
            }
        }
        if (!encontrado)dtm.addRow(aux);
       /* buscarActionPerformed(e);
        tblPares.setRowSelectionInterval(tblPares.getRowCount()-1, tblPares.getRowCount()-1);*/
        
    }

    private void modificarActionPerformed(ActionEvent e) {
        String parIncorrecto = String.valueOf(txtParI.getText());
        String parCorrecto = String.valueOf(txtParC.getText());
        int[] sel = tblPares.getSelectedRows();
        if (sel.length < 1) mensaje("par no seleccionado");
        else  {
            for (int i = 0; i < sel.length; ++i) {
                cicp.modificarPar(String.valueOf(tblPares.getValueAt(sel[i], 1))
                        , String.valueOf(tblPares.getValueAt(sel[i], 0)), parCorrecto, parIncorrecto);
                tblPares.setValueAt(parIncorrecto, sel[i], 0);
                tblPares.setValueAt(parCorrecto, sel[i], 1);
            }
        }
    }

    private void eliminarActionPerformed(ActionEvent e) {
        int[] sel = tblPares.getSelectedRows();
        if (sel.length < 1) mensaje("par no seleccionado");
        else  {
            String parI = String.valueOf(tblPares.getValueAt(sel[0], 0));
            String parC = String.valueOf(tblPares.getValueAt(sel[0], 1));
            cicp.eliminarPar(parC, parI);
            boolean encontrado = false;
            actualizarEliminacion (parC, parI, encontrado);
        }
    }

    private boolean actualizarEliminacion (String parC, String parI, boolean encontrado){
        for (int i = 0; i < tblPares.getRowCount() && !encontrado; ++i){
                if (String.valueOf(tblPares.getValueAt(i, 0)).equals(parI) && String.valueOf(tblPares.getValueAt(i, 1)).equals(parC)) {
                    encontrado = true;
                    String [] res = new String[3];
                    res = cicp.buscarPar(parC, parI);
                    if (res == null)dtm.removeRow(i);
                    else {
                        String aux = String.valueOf(res[2]);
                        tblPares.setValueAt(aux, i, 2);
                }
            }
        }
        return encontrado;
    }

    private void buscarActionPerformed(ActionEvent e) {
        String parIncorrecto = String.valueOf(txtParI.getText());
        String parCorrecto = String.valueOf(txtParC.getText());
        /*boolean encontrado = false;
        for (int i = 0; i < tblPares.getRowCount() && !encontrado; ++i) {
            if (String.valueOf(tblPares.getValueAt(i, 0)).equals(parIncorrecto)
                    && String.valueOf(tblPares.getValueAt(i, 1)).equals(parCorrecto)) {
                encontrado = true;
                tblPares.setRowSelectionInterval(i, i);
                int max = jspTblPares.getVerticalScrollBar().getMaximum();
                int mult = (max) / cicp.longitudPares();
                int posicion = jspTblPares.getVerticalScrollBar().getMinimum()+i*mult;
                if (posicion > max) posicion = max;
                jspTblPares.getVerticalScrollBar().setValue(posicion);
            }
        }
        if (!encontrado)mensaje("par no encontrado");*/
        int i=cicp.buscarIndicePar(parCorrecto, parIncorrecto);
        if (i>=0){
                tblPares.setRowSelectionInterval(i, i);
                int max = jspTblPares.getVerticalScrollBar().getMaximum();
                int mult = (max) / cicp.longitudPares();
                int posicion = jspTblPares.getVerticalScrollBar().getMinimum()+i*mult;
                if (posicion > max) posicion = max;
                jspTblPares.getVerticalScrollBar().setValue(posicion);
        } else {
            this.mensaje("Par no encontrado");
        }
    }
    private void inicializarPanelNoHayCP(){
        pNoHayCP.setVisible(true);

    }

    private void inicializarLayoutPanelNoHayCP(){
        pNoHayCP.setLayout(lyPanelNoHayCP);
        lyPanelNoHayCP.putConstraint(SpringLayout.NORTH, lbNoHayCP, 0, SpringLayout.NORTH, pNoHayCP);
        lyPanelNoHayCP.putConstraint(SpringLayout.SOUTH, lbNoHayCP, 0, SpringLayout.SOUTH, pNoHayCP);
        lyPanelNoHayCP.putConstraint(SpringLayout.EAST, lbNoHayCP, 0, SpringLayout.EAST, pNoHayCP);
        lyPanelNoHayCP.putConstraint(SpringLayout.WEST, lbNoHayCP, 0, SpringLayout.WEST, pNoHayCP);
    }
    private void inicializarPanel(){
        pares.setVisible(false);
        this.setBorder(BorderFactory.createTitledBorder(BorderFactory.createLineBorder(Color.GRAY), "Conjunto de Pares"));

    }
    private void inicializarPanelPares(){
        pares.setBorder(BorderFactory.createTitledBorder(BorderFactory.createLineBorder(Color.GRAY), "Pares"));
    }
    public void montar(){
        dgCargar.getContentPane().add(jpbCargar);
        //this.add(dgCargar);
        pNoHayCP.add(lbNoHayCP);
        pares.add(jspTblPares);
        pares.add(btnBuscarPar);
        pares.add(btnNuevoPar);
        pares.add(btnModificarPar);
        pares.add(btnEliminarPar);
        pares.add(txtParI);
        pares.add(txtParC);
        pares.add(jlparI);
        pares.add(jlparC);
        this.add(pares);
        this.add(pNoHayCP);

    }
    private void inicializarLayout(){
        this.setLayout(layout);
        layout.putConstraint(SpringLayout.NORTH, pares, 5, SpringLayout.NORTH, this);
        layout.putConstraint(SpringLayout.EAST, pares, -10, SpringLayout.EAST, this);
        layout.putConstraint(SpringLayout.SOUTH, pares, -10, SpringLayout.SOUTH, this);
        layout.putConstraint(SpringLayout.WEST, pares, 10, SpringLayout.WEST, this);
       layout.putConstraint(SpringLayout.WEST, pNoHayCP, 0, SpringLayout.WEST, this);
        layout.putConstraint(SpringLayout.EAST, pNoHayCP, 0, SpringLayout.EAST, this);
        layout.putConstraint(SpringLayout.NORTH, pNoHayCP, 0, SpringLayout.NORTH, this);
        layout.putConstraint(SpringLayout.SOUTH, pNoHayCP, 0, SpringLayout.SOUTH, this);
    }
        
    private void inicializarLayoutPares(){
        pares.setLayout(layoutPares);
        layoutPares.putConstraint(SpringLayout.EAST, jspTblPares, -10, SpringLayout.EAST, pares);
        layoutPares.putConstraint(SpringLayout.WEST, jspTblPares, 10, SpringLayout.WEST, pares);
        layoutPares.putConstraint(SpringLayout.NORTH, jspTblPares, 10, SpringLayout.NORTH, pares);
        layoutPares.putConstraint(SpringLayout.SOUTH, jspTblPares, -120, SpringLayout.SOUTH, pares);
        layoutPares.putConstraint(SpringLayout.NORTH, btnNuevoPar, 10, SpringLayout.SOUTH, jspTblPares);
        layoutPares.putConstraint(SpringLayout.EAST, btnNuevoPar, -10, SpringLayout.HORIZONTAL_CENTER, pares);
        layoutPares.putConstraint(SpringLayout.WEST, btnNuevoPar, 0, SpringLayout.WEST, jspTblPares);
        layoutPares.putConstraint(SpringLayout.NORTH, btnEliminarPar, 0, SpringLayout.NORTH, btnNuevoPar);
        layoutPares.putConstraint(SpringLayout.WEST, btnEliminarPar, 10, SpringLayout.HORIZONTAL_CENTER, pares);
        layoutPares.putConstraint(SpringLayout.EAST, btnEliminarPar, 0, SpringLayout.EAST, jspTblPares);
        layoutPares.putConstraint(SpringLayout.NORTH, btnModificarPar, 5, SpringLayout.SOUTH, btnNuevoPar);
        layoutPares.putConstraint(SpringLayout.EAST, btnModificarPar, -10, SpringLayout.HORIZONTAL_CENTER, pares);
        layoutPares.putConstraint(SpringLayout.WEST, btnModificarPar, 0, SpringLayout.WEST, jspTblPares);
        layoutPares.putConstraint(SpringLayout.NORTH, btnBuscarPar, 0, SpringLayout.NORTH, btnModificarPar);
        layoutPares.putConstraint(SpringLayout.WEST, btnBuscarPar, 10, SpringLayout.HORIZONTAL_CENTER, pares);
        layoutPares.putConstraint(SpringLayout.EAST, btnBuscarPar, 0, SpringLayout.EAST, btnEliminarPar);
        layoutPares.putConstraint(SpringLayout.NORTH, txtParI, 5, SpringLayout.SOUTH, btnBuscarPar);
        layoutPares.putConstraint(SpringLayout.WEST, txtParI, 75, SpringLayout.WEST, btnNuevoPar);
        layoutPares.putConstraint(SpringLayout.EAST, txtParI, 0, SpringLayout.EAST, btnEliminarPar);
        layoutPares.putConstraint(SpringLayout.NORTH, txtParC, 5, SpringLayout.SOUTH, txtParI);
        layoutPares.putConstraint(SpringLayout.WEST, txtParC, 75, SpringLayout.WEST, btnNuevoPar);
        layoutPares.putConstraint(SpringLayout.EAST, txtParC, 0, SpringLayout.EAST, btnEliminarPar);

        jlparI.setSize(20, 30);
        jlparC.setSize(20, 30);
        layoutPares.putConstraint(SpringLayout.NORTH, jlparI, 5, SpringLayout.SOUTH, btnBuscarPar);
        layoutPares.putConstraint(SpringLayout.WEST, jlparI, 0, SpringLayout.WEST, btnNuevoPar);
        layoutPares.putConstraint(SpringLayout.NORTH, jlparC, 5, SpringLayout.SOUTH, txtParI);
        layoutPares.putConstraint(SpringLayout.WEST, jlparC, 0, SpringLayout.WEST, btnNuevoPar);
        jlparI.setText("Incorrecta: ");
        jlparC.setText("Correcta: ");
    }

    public void anadirPares(String[][] conjpares, String titulo){
        limpiar();
        inicializarTab();
        for (int i = 0; i < conjpares.length; ++i) {
            dtm.addRow(conjpares[i]);
        }
       // inicializarPanel();
        //inicializarLayoutPares();
        //montar();
    }
    public void mostrarError(String textoError,Component cent){
        JOptionPane.showMessageDialog(null, textoError);
    }
    public void mensaje(String mensaje){
        mensaje(this,mensaje);
    }
    public void mensaje(Component cent, String mensaje){
        JOptionPane.showMessageDialog(cent, mensaje);
    }
    public String[][] obtenerPares () {
        tblPares.setModel(dtm);
        String [][] conjpares = new String[/*dtm.getRowCount()*/1][2];
        for (int i = 0; i < 1/*dtm.getRowCount()*/; ++i){
            conjpares[i][0] = (String) dtm.getValueAt(i, 0);
            conjpares[i][1] = (String) dtm.getValueAt(i, 1);
        }
        return conjpares;
    }

    /*public void eliminartabla() {
        int h;
        int tam = dtm.getRowCount();
        for(h = 0; h < tam; ++h) dtm.removeRow(dtm.getRowCount()-1);
   }*/
   public void limpiar(){
        dtm = construirTableModel(0);
        tblPares.setModel(dtm);
        tblPares.setModel(dtm);
    }
    public void cambiarANoCP(){
        pares.setVisible(false);
        pNoHayCP.setVisible(true);
    }
    public void cambiarAPares(){
        pares.setVisible(true);
        pNoHayCP.setVisible(false);
    }

}